
import { CallHandler, ExecutionContext, Injectable, NestInterceptor, UseInterceptors, applyDecorators, createParamDecorator } from "@nestjs/common"
import { Observable, tap } from "rxjs";
import { LogService } from "./log.service";
import { Request, Response } from "express";
import { ApiOperation } from "@nestjs/swagger";


export const UseLog = (summary?: string | { summary: string }) => {
    const name = typeof summary === "string" ? summary : summary.summary
    @Injectable()
    class UseLogInterceptor implements NestInterceptor {
        constructor(
            private readonly logService: LogService
        ) { }

        intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
            const request: Request = context.switchToHttp().getRequest();
            return next.handle().pipe(
                tap((data) => {
                    const response: Response = context.switchToHttp().getResponse();
                    const { method, user } = request as any;
                    let body = request.body;
                    try {
                        body = JSON.stringify(body)
                        if (body.length > 1024) body = "数据过大"
                    } catch (e) { }
                    try {
                        data = JSON.stringify(data)
                        if (data.length > 2048) data = "数据过大"
                    } catch (e) { }
                    this.logService.create(
                        user,
                        name,
                        request.url,
                        method,
                        response.statusCode,
                        body,
                        data,
                        user.login_ip
                    )
                }),
            );
        }
    }
    return applyDecorators(
        ApiOperation({ summary: name }),
        UseInterceptors(UseLogInterceptor)
    )
}